package com.openai.chatgpt.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.openai.chatgpt.utils.ChatGPT;
import com.openai.chatgpt.utils.Proxys;
import com.theokanning.openai.client.OpenAiApi;
import com.theokanning.openai.service.OpenAiService;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit2.Retrofit;

import java.net.Proxy;
import java.time.Duration;

/**
 * 聊天gpt config
 *
 * @author Amadeus
 * @date 2024/02/18
 */
@Configuration
public class ChatGPTConfig {

    @Value("${chatgpt.apiKey}")
    private String apiKey;

    @Value("${chatgpt.proxy.host}")
    private String proxyHost;

    @Value("${chatgpt.proxy.port}")
    private int proxyPort;

    @Bean
    public ChatGPT customizingChatGPT() {
        Proxy proxy = Proxys.http(proxyHost, proxyPort);
        return ChatGPT.builder()
                .apiKey(apiKey)
                .timeout(900)
                .proxy(proxy)
                .build()
                .init();
    }

    @Bean
    public OpenAiService openAiService() {
        ObjectMapper mapper = OpenAiService.defaultObjectMapper();
        Proxy proxy = Proxys.http(proxyHost, proxyPort);
        OkHttpClient client = OpenAiService.defaultClient(apiKey, Duration.ofSeconds(900L))
                .newBuilder()
                .proxy(proxy)
                .build();
        Retrofit retrofit = OpenAiService.defaultRetrofit(client, mapper);
        OpenAiApi api = retrofit.create(OpenAiApi.class);
        return new OpenAiService(api);
    }

}
